
import { Vec2 } from 'cc';
import { ScrollView, Node } from 'cc';
import { _decorator, Component } from 'cc';
import { App } from '../../App';
import { Cue } from './Cue';
import { GamePlayState } from './GameBaseLogic';
import { GameBaseModel } from './GameBaseModel';
import { GameModel3 } from './mode3/GameModel3';
const { ccclass, property } = _decorator;

/* 球杆刻度尺 */
@ccclass('CueDial')
export class CueDial extends Component {
    @property(ScrollView)
    dialScroll: ScrollView = null;

    @property(Node)
    content: Node = null;

    // 滚动视图位置
    contentPos = new Vec2(0, 0)

    // 滚动视图Y轴偏移量
    lastOffsetY = 0

    // 微调参数
    angleRate = 0.01

    // 是否移动了刻度尺
    isMove = false

    private cueCtrl:Cue = null  // 球杆对象

    onLoad(): void {
        
    }

    start() {
        let gameView = App.Model.gameView as GameBaseModel
        this.cueCtrl = gameView.cueCtrl
        this.lastOffsetY = this.dialScroll.getScrollOffset().y
    }

    update () {
        if (!this.judgeValid()) return

        let scrollOffset: Vec2 = this.dialScroll.getScrollOffset()
        let offset = scrollOffset.y

        // 0  1083
        if (offset>=1073){ // 往上滑动
            this.dialScroll.scrollToTop()
            this.contentPos.y = 11
            this.dialScroll.scrollToOffset(this.contentPos)
            this.lastOffsetY = this.contentPos.y
        }
        else if (offset<=10) { // 往下滑动
            this.dialScroll.scrollToBottom()
            this.contentPos.y = 1072
            this.dialScroll.scrollToOffset(this.contentPos)
            this.lastOffsetY = this.contentPos.y
        }
        else{
            let disY = offset - this.lastOffsetY

            if (Math.abs(disY) > 0.001) {
                if (!this.isMove) {
                    App.Audio.playOneShot("cueDial")
                }

                // 正在滑动
                this.isMove = true
                let angle = -disY * this.angleRate

                // 杆子旋转角度
                this.cueCtrl.setCueRotation(angle)
            }
            else{
                // 停止滑动
                if (this.isMove) {
                    let gameView = App.Model.gameView as GameBaseModel
                    gameView.reqChangeCueMsg(this.cueCtrl.ballToCueAngle(this.cueCtrl.cueAngle))
                }
                
                this.isMove = false
            }
            this.lastOffsetY = offset
          
        }
    }

    // 判断是否可以操作能量条
    judgeValid() {
        if (this.cueCtrl==null) {
            return false
        }
        
        //球杆隐藏时操作无效
        if (!this.cueCtrl.node.active || !this.cueCtrl.isMine) {
            return false
        }

        // 摆球阶段操作无效
        let gameView = App.Model.gameView as GameModel3
        if (gameView && gameView.gameLogic &&  gameView.gameLogic.curPlayState == GamePlayState.WAIT_POS_BALL) {
            return false
        } 

        return true
    }

}

